﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace RESP_IIWaterAssessment
{
    public partial class ConflictReportForm : Form
    {
        public ConflictReportForm()
        {
            InitializeComponent();
        }

        int regid, avpID;

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbRegion.SelectedIndex >= 0)
            {
                regid = Convert.ToInt32(cbRegion.SelectedValue);

                cbAVP.Enabled = true;
                //cbAVP.Items.Clear();
                cbAVP.Text = string.Empty;
                cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;
                cbAVP.DataSource = DBClass.AVP
                    .Where(wh => wh.RegionID == Convert.ToInt32(regid))
                    .Select(se => new
                    {
                        NameAVP = se.Name,
                        ID = se.ID
                    }).ToList();
                cbAVP.DisplayMember = "NameAVP";
                cbAVP.ValueMember = "ID";
                cbAVP.SelectedIndex = -1;
                cbAVP.Text = string.Empty;
                cbAVP.SelectedIndexChanged += new EventHandler(cbAVP_SelectedIndexChanged);

            }
        }

        private void cbAVP_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbAVP.SelectedIndex >= 0)
                avpID = Convert.ToInt32(cbAVP.SelectedValue);
        }

        private void ConflictReportForm_Load(object sender, EventArgs e)
        {
            nudYear.Enabled = false;

            cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;

            cbRegion.DataSource = DBClass.Regions.Select(se => new
            {
                Name = se.Name,
                ID = se.ID
            }).ToList();
            cbRegion.ValueMember = "ID";
            cbRegion.DisplayMember = "Name";
            cbRegion.SelectedIndex = -1;
            cbRegion.Text = string.Empty;

            cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);

            cbRegionResultConflict.SelectedIndexChanged -= cbRegionResultConflict_SelectedIndexChanged;

            cbRegionResultConflict.DataSource = DBClass.Regions.Select(se => new
            {
                Name = se.Name,
                ID = se.ID
            }).ToList();
            cbRegionResultConflict.ValueMember = "ID";
            cbRegionResultConflict.DisplayMember = "Name";
            cbRegionResultConflict.SelectedIndex = -1;
            cbRegionResultConflict.Text = string.Empty;

            cbRegionResultConflict.SelectedIndexChanged += new EventHandler(cbRegionResultConflict_SelectedIndexChanged);

            if (InformationClass.isAdmin)
            {
                // конфликты авп
                
                cbAVP.Enabled = false;


                // рез-ты конфликтов
                
                cbAVPResultConflict.Enabled = false;

            }
            else
            {
                cbRegion.Enabled = cbRegionResultConflict.Enabled = false;

                regid = InformationClass.regionID;
                cbRegionResultConflict.SelectedValue = regid;
                cbRegion.SelectedValue = regid;
                //cbAVP.DataSource = cbAVPResultConflict.DataSource = DBClass.AVP
                //                                                            .Where(wh => wh.RegionID == regid)
                //                                                            .Select(se => new { ID = se.ID, Name = se.Name })
                //                                                            .OrderBy(o => o.Name)
                //                                                            .ToArray();


                cbRegion_SelectedIndexChanged(cbRegion, null);
                cbRegionResultConflict_SelectedIndexChanged(cbRegionResultConflict, null);
            }


            if (InformationClass.Lang)
                cbConflictType.Items.AddRange(new object[]{ "Между сотрудниками АВП",
                "АВП с УИСом",
                "АВП с Водопотребители",
                "Между водопотребителями"});
            else
                cbConflictType.Items.AddRange(new object[]{ "СИУ ходимлари ўртасида",
                "СИУ  билан ИТБ",
                "СИУ билан сув истеъмолчилари ",
                "Су истеъмолчилари"});

        }

        private void buttonShow_Click(object sender, EventArgs e)
        {
            isResultConf = false;

            int? aID = null, rID = null, year = null;

            if (cbAVP.SelectedIndex >= 0)
                aID = Convert.ToInt32(cbAVP.SelectedValue);
            else if (cbRegion.SelectedIndex >= 0)
                rID = Convert.ToInt32(cbRegion.SelectedValue);
            if (chbYear.Checked)
                year = (int)nudYear.Value;

            dgvConflicts.DataSource = DBClass.RESPContext.ConflictCounts(rID, aID, year);
            if (InformationClass.Lang)
            {
                dgvConflicts.Columns["Name"].HeaderText = "АВП";
                dgvConflicts.Columns["CAVPvsUIS"].HeaderText = "АВП и УИС";
                dgvConflicts.Columns["CAVPvsWU"].HeaderText = "АВП и Водопользывателями";
                dgvConflicts.Columns["CAVPvsAVP"].HeaderText = "Между членами АВП";
                dgvConflicts.Columns["CWUvsWU"].HeaderText = "Между водопользователями";
            }
            else
            {
                dgvConflicts.Columns["Name"].HeaderText = "СИУ номи";
                dgvConflicts.Columns["CAVPvsUIS"].HeaderText = "СИУ ва ИТБ";
                dgvConflicts.Columns["CAVPvsWU"].HeaderText = "СИУ ва сувдан фойдаланувчилар";
                dgvConflicts.Columns["CAVPvsAVP"].HeaderText = "СИУ аъзолари ўртасида";
                dgvConflicts.Columns["CWUvsWU"].HeaderText = "Сувдан фойдалунувчилар ўртасида";
            }

        }

        private void chbYear_CheckedChanged(object sender, EventArgs e)
        {
            nudYear.Enabled = chbYear.Checked;
        }

        private void chbFromDate_CheckedChanged(object sender, EventArgs e)
        {
            label5.Visible = dtpToDate.Enabled = chbFromDate.Checked;
        }

        private void buttonShowResultConflict_Click(object sender, EventArgs e)
        {
            isResultConf = true;

            int? aID, conType = null;
            DateTime? DFrom, DTo;
            bool? Res, InJ;

            if (cbAVPResultConflict.SelectedIndex >= 0)
                aID = avpID;
            else
                aID = null;

            if (chbConflictType.Checked && cbConflictType.SelectedIndex >= 0)
            {
                switch ((cbConflictType.SelectedIndex))
                {
                    case 0:
                        conType = (int)InformationClass.ConflictObject.AVPvsAVP;
                        break;
                    case 1:
                        conType = (int)InformationClass.ConflictObject.AVPvsUIS;
                        break;
                    case 2:
                        conType = (int)InformationClass.ConflictObject.AVPvsWU;
                        break;
                    case 3:
                        conType = (int)InformationClass.ConflictObject.WUvsWU;
                        break;
                    default:
                        conType = null;
                        break;
                }
            }

            if (chbDate.Checked)
            {
                DFrom = dtpFrom.Value.Date;
                if (chbFromDate.Checked)
                {
                    DTo = dtpToDate.Value.Date;
                }
                else
                {
                    DTo = null;
                }
            }
            else
                DFrom = DTo = null;

            if (chbResult.Checked)
                Res = rbPositive.Checked;
            else
                Res = null;

            if (chbJournal.Checked)
            {
                InJ = rbJYes.Checked;
            }
            else
                InJ = null;

            dgvConflicts.DataSource = DBClass.RESPContext.ConflictResults(aID, conType, DFrom, DTo, Res, InJ);

            if (InformationClass.Lang)
            {
                dgvConflicts.Columns["Name"].HeaderText = "АВП";
                dgvConflicts.Columns["Date"].HeaderText = "Дата конфликта";
                dgvConflicts.Columns["ConflictType"].HeaderText = "Тип конфликта";
                dgvConflicts.Columns["Result"].HeaderText = "Результат";
                dgvConflicts.Columns["IsInJournal"].HeaderText = "Запись в журнале";
            }
            else
            {
                dgvConflicts.Columns["Name"].HeaderText = "СИУ";
                dgvConflicts.Columns["Date"].HeaderText = "Низо санаси";
                dgvConflicts.Columns["ConflictType"].HeaderText = "Низо тури";
                dgvConflicts.Columns["Result"].HeaderText = "Натижа";
                dgvConflicts.Columns["IsInJournal"].HeaderText = "Журналга қайд қилиш";
            }

            dgvConflicts.AutoResizeColumns();
        }

        private void cbRegionResultConflict_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbRegionResultConflict.SelectedIndex >= 0)
            {
                regid = Convert.ToInt32(cbRegionResultConflict.SelectedValue);

                cbAVPResultConflict.Enabled = true;
                //cbAVP.Items.Clear();
                cbAVPResultConflict.Text = string.Empty;
                cbAVPResultConflict.SelectedIndexChanged -= cbAVPResultConflict_SelectedIndexChanged;
                cbAVPResultConflict.DataSource = DBClass.AVP
                    .Where(wh => wh.RegionID == Convert.ToInt32(regid))
                    .Select(se => new
                    {
                        NameAVP = se.Name,
                        ID = se.ID
                    }).ToList();
                cbAVPResultConflict.DisplayMember = "NameAVP";
                cbAVPResultConflict.ValueMember = "ID";
                cbAVPResultConflict.SelectedIndex = -1;
                cbAVPResultConflict.Text = string.Empty;
                cbAVPResultConflict.SelectedIndexChanged += new EventHandler(cbAVPResultConflict_SelectedIndexChanged);

            }
        }

        private void cbAVPResultConflict_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbAVPResultConflict.SelectedIndex >= 0)
            {
                avpID = Convert.ToInt32(cbAVPResultConflict.SelectedValue);
            }

        }

        private void chbConflictType_CheckedChanged(object sender, EventArgs e)
        {
            cbConflictType.Enabled = chbConflictType.Checked;
        }

        private void chbResult_CheckedChanged(object sender, EventArgs e)
        {
            groupBox1.Enabled = chbResult.Checked;
        }

        private void chbJournal_CheckedChanged(object sender, EventArgs e)
        {
            groupBox2.Enabled = chbJournal.Checked;
        }

        private void chbDate_CheckedChanged(object sender, EventArgs e)
        {
            if (!chbDate.Checked)
                chbFromDate.Checked = false;
            chbFromDate.Enabled = chbDate.Checked;
        }

        private void dgvConflicts_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dgvConflicts.Columns.Contains("Result"))
            {
                if (e.ColumnIndex.Equals(dgvConflicts.Columns["Result"].Index) && e.Value != null)
                {
                    string ResTrue = InformationClass.Lang ? "Положительный" : "Ижобий";
                    string ResFalse = InformationClass.Lang ? "Отрицательный" : "Салбий";

                    string newVal = (bool)e.Value ? ResTrue : ResFalse;
                    if (String.IsNullOrEmpty(newVal))
                        e.Value = "no data";
                    else
                        e.Value = newVal;
                }
            }
            if (dgvConflicts.Columns.Contains("IsInJournal"))
            {
                if (e.ColumnIndex.Equals(dgvConflicts.Columns["IsInJournal"].Index) && e.Value != null)
                {
                    string ResTrue = InformationClass.Lang ? "Есть" : "Ха";
                    string ResFalse = InformationClass.Lang ? "Нет" : "Йук";

                    string newVal = (bool)e.Value ? ResTrue : ResFalse;
                    if (String.IsNullOrEmpty(newVal))
                        e.Value = "no data";
                    else
                        e.Value = newVal;
                }
            }
            if (dgvConflicts.Columns.Contains("ConflictType"))
            {
                if (e.ColumnIndex.Equals(dgvConflicts.Columns["ConflictType"].Index) && e.Value != null)
                {
                    string newVal = cbConflictType.Items[(int)e.Value].ToString();
                    if (String.IsNullOrEmpty(newVal))
                        e.Value = "no data";
                    else
                        e.Value = newVal;
                }
            }
        }

        bool isResultConf = false;

        Sheets excelsheets;
        Worksheet excelworksheet;
        Microsoft.Office.Interop.Excel.Application excelapp;
        Workbook excelappworkbook;
        Workbooks excelappworkbooks;

        private void buttonExcel_Click(object sender, EventArgs e)
        {
            if (dgvConflicts.RowCount > 0)
            {
                if (isResultConf)
                {
                    MessageBox.Show(msgClass.msgWaiting);
                    GetReport();
                    excelworksheet.Select(1);
                    excelapp.Visible = true;
                }
                else
                {
                    //GetReportConflict();
                }

            }
        }

        private void GetReportConflict()
        {
            excelapp = new Microsoft.Office.Interop.Excel.Application();
            excelapp.SheetsInNewWorkbook = 1;

            if (InformationClass.Lang)
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\r5.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            else
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\r5uz.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            excelappworkbook = excelapp.Workbooks[1];
            excelsheets = excelappworkbook.Worksheets;// .Worksheets[0]; //Sheets 
            excelworksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelsheets.get_Item(1);

            //int left = 3, top = 8;
            //excelworksheet.Cells.NumberFormat = "@";

            //if (cbRegion.SelectedIndex >= 0)
            //    excelworksheet.Cells[4, 2] = cbRegion.Text;

            //for (int i = 0; i < dgvConflicts.Rows.Count; i++)
            //{
            //    for (int j = 1; j < dgvConflicts.Columns.Count; j++)
            //    {
            //        excelworksheet.Cells[i + top, dgvConflicts.Columns[j].DisplayIndex + left] = dgvConflicts[j, i].FormattedValue;
            //        addBorder(excelworksheet.Cells[i + top, dgvConflicts.Columns[j].DisplayIndex + left]);
            //    }

            //    excelworksheet.Cells[i + top, 2] = i + 1;
            //    addBorder(excelworksheet.Cells[i + top, 2]);
            //    //excelworksheet.Cells[i + 9, 3] = UtilClass.GetRegionName((string)dgvConflicts["Name", i].Value);
            //}
            //excelworksheet.Columns.AutoFit();
        }

        private void GetReport()
        {
            excelapp = new Microsoft.Office.Interop.Excel.Application();
            excelapp.SheetsInNewWorkbook = 1;

            if (InformationClass.Lang)
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\r5.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            else
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\r5uz.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            excelappworkbook = excelapp.Workbooks[1];
            excelsheets = excelappworkbook.Worksheets;// .Worksheets[0]; //Sheets 
            excelworksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelsheets.get_Item(1);

            int left = 3, top = 8;
            excelworksheet.Cells.NumberFormat = "@";

            if (cbRegionResultConflict.SelectedIndex >= 0)
                excelworksheet.Cells[4, 3] = cbRegionResultConflict.Text;
            if (chbFromDate.Checked)
                excelworksheet.Cells[5, 3] = dtpFrom.Value.Year.ToString();

            for (int i = 0; i < dgvConflicts.Rows.Count; i++)
            {
                for (int j = 0; j < dgvConflicts.Columns.Count; j++)
                {
                    excelworksheet.Cells[i + top, dgvConflicts.Columns[j].DisplayIndex + left] = dgvConflicts[j, i].FormattedValue;
                    addBorder(excelworksheet.Cells[i + top, dgvConflicts.Columns[j].DisplayIndex + left]);
                }

                excelworksheet.Cells[i + top, 2] = i + 1;
                addBorder(excelworksheet.Cells[i + top, 2]);
                //excelworksheet.Cells[i + 9, 3] = UtilClass.GetRegionName((string)dgvConflicts["Name", i].Value);
            }
            excelworksheet.Columns.AutoFit();

        }

        private void addBorder(object p)
        {
            Range tmpRange = excelworksheet.get_Range(p, p);
            tmpRange.Borders[XlBordersIndex.xlEdgeLeft].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeRight].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            if (isResultConf && dgvConflicts.RowCount > 0)
            {
                PrintDGV.Print_DataGridView(dgvConflicts);
            }
        }
    }
}
